<template>
  <div class="container">
    <el-card>
      <div slot="header" v-if="subject.id && subject.name">
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item>学科管理</el-breadcrumb-item>
    <el-breadcrumb-item>{{subject.name}}</el-breadcrumb-item>
    <el-breadcrumb-item>目录管理</el-breadcrumb-item>
    </el-breadcrumb>
      </div>
      <el-form ref="form" :model="requestParameters" label-width="80px">
        <el-row >
          <!-- 输入框 -->
          <el-col :span="5">
            <el-form-item label="目录名称">
              <el-input v-model="requestParameters.directoryName" style="width: 120px"></el-input>
            </el-form-item>
          </el-col>
          <!-- 选择框 -->
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="requestParameters.state" placeholder="请选择" @keyup.enter="handleFilter">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 按钮 -->
          <el-col :span="9">
            <el-button @click="empty">清除</el-button>
            <el-button type="primary" @click="handleFilter">搜索</el-button>
          </el-col>
          <el-col :span="4">

            <el-button  v-if="subject.id && subject.name"
            type="text"
            icon="el-icon-back"
            @click="$router.push('/subjects/list')">返回学科</el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              @click="handleChangeAdd('add','')"
              >新增目录</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <!-- 记录 -->
      <el-alert :title="alertText" type="info" show-icon :closable="false"> </el-alert>
      <!-- 表格 -->
      <el-table :data="dataList" style="width: 100%">
        <el-table-column  align="center" label="序号" width="100" type="index" :index="indexMethod">
        </el-table-column>
        <el-table-column
          prop="subjectName"
          label="所属学科"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column prop="directoryName" align="center" label="目录名称" width="150">
        </el-table-column>
        <el-table-column prop="username" align="creatorID" label="创建者" >
        </el-table-column>
        <el-table-column  align="center" label="创建日期" width="250">
          <template #default="{row}">
            {{row.addDate | parseTimeByString}}
          </template>
        </el-table-column>
        <el-table-column prop="totals" align="center" label="面试题数量">
        </el-table-column>
        <el-table-column prop="state" align="center" label="状态" :formatter="formatState">
          <!-- <template slot-scope="scope">
            <span>{{ scope.row.state }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="operation"
          align="center"
          label="操作"
          width="280"
        >
          <template #default="{row}">
            <el-button size="mini" @click="handleStatus(row)"  type="text">
           {{row.state===1 ? '禁用' : '启用'}}
            </el-button>
            <el-button size="mini" @click="handleChangeAdd('edit',row.id)"
              :disabled="row.state===1" type="text"
              >修改</el-button
            >
            <el-button size="mini" @click="removeUser(row)"
              :disabled="row.state===1" type="text">删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
     <div class="pagination">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="Number(requestParameters.page)"
        :page-size="Number(requestParameters.pagesize)"
        :page-sizes="[2, 4, 6, 8,10,12,14,16,20]"
        :total="counts"
        layout=" total, prev, pager, next, sizes, jumper"
      >
      </el-pagination>
     </div>
      <!-- 弹框 -->
      <el-dialog
        :title="titleInfo.text + titleInfo.pageTitle"
        :visible="dialogAdd"
        width="400px"
        type="primary"
        @close='closeDialog'
      >
        <el-form
          :model="formData"
          ref="ruleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id">
            <el-select v-model="formData.subjectID" placeholder="请选择" @click="handleSubject">
              <el-option v-for="item in directorysList" :key="item.value" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="directoryName">
            <el-input
              v-model="formData.directoryName"
              placeholder="请输入目录名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="closeDialog">取消</el-button>
            <el-button @click="createData" type="primary">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import Dialog from './../components/directorys-add.vue'
import { list, remove, changeState, add, update, detail } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects.js'
// import { parseTimeByString } from '@/filters/index.js'
import { status } from '@/api/hmmm/constants.js'
export default {
  name: 'Directorys',
  data () {
    return {
      alertText: null,
      dialogAdd: false,
      dataList: [],
      counts: 1,
      directorysList: [],
      form: {
        subName: null
        // state: null
      },
      // 弹窗名称
      titleInfo: {
        pageTitle: '目录', // 页面标题
        text: '' // 新增、编辑文本
      },
      options: [{
        value: '1',
        label: '启用'
      }, {
        value: '0',
        label: '禁用'
      }],

      formData: {
        subjectID: null,
        directoryName: null

      },
      requestParameters: {
        page: 1,
        pagesize: 10,
        directoryName: null,
        state: null,
        subjectID: null
      },
      rules: {
        subjectName: [
          { required: true, message: '所属学科不能为空', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '目录名称不能为空', trigger: ['blur', 'change'] }
        ]
      },
      value: ''
    }
  },
  prop: {
    titleInfo: Object
  },
  computed: {
    subject () {
      return this.$route.query || {}
    },
    routerId () {
      return this.$route.query.id
    }
  },
  created () {
    console.log(this.$route.query)
    this.getList()
    this.formatState()
  },
  methods: {
    // 序号相关
    indexMethod (index) {
      return index + 1 + this.requestParameters.pagesize * (this.requestParameters.page - 1)
    },
    closeDialog () {
      this.dialogAdd = false
      this.formData = {}
      this.$refs.ruleForm.resetFields()
    },
    // 格式化状态
    formatState (row, column, cellValue, index) {
      const temp = status.find(item => item.value === +cellValue)
      return temp ? temp.label : '未知'
    },

    // 获取列表数据
    async getList () {
      this.listLoading = true
      const { data } = await list({
        ...this.requestParameters,
        subjectID: this.routerId || null
      })
      // console.log(res)
      // dataList获取数据

      console.log(data)
      this.dataList = data.items
      // 获取总数
      this.counts = data.counts
      this.total = data.counts
      // console.log(items.counts)
      this.alertText = `数据一共 ${data.counts} 条`
      this.listLoading = false
    },
    // 每页显示信息条数
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.requestParameters.pagesize = val
      if (this.requestParameters.page === 1) {
        this.getList(this.requestParameters)
      }
    },
    // 进入选中页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.requestParameters.page = val
      this.getList()
    },

    // 打开表单--新增和修改
    async  handleChangeAdd (m1, m2) {
      if (m1 === 'add') {
        this.titleInfo.text = '创建'
        this.dialogAdd = true
        const res = await simple(this.formData)
        // console.log(res)
        this.directorysList = res.data
      } else {
        const { data: newData } = await simple(this.formData)

        this.directorysList = newData
        this.titleInfo.text = '编辑'
        this.dialogAdd = true
        const { data } = await detail({ id: m2 })
        // console.log(res)
        // console.log(data, 9999999999)
        this.formData = data
      }
    },

    // 启用禁用
    async handleStatus (row) {
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }

      const res = changeState({ id: row.id, state: row.state })
      console.log(res)
      // await changeState({
      //   id: val.id,
      //   state: val.status === 1 ? 0 : 1
      // })
      // this.$message.success('操作成功')
      // val.state = val.state === 1 ? 0 : 1
    },
    // 关闭表单
    // dialogFromH () {
    //   this.dialogAdd = false
    //   this.formData = {}
    //   this.$refs.ruleForm.resetFields()
    // },
    // 清除输入框
    empty () {
      this.requestParameters.directoryName = ''
      this.requestParameters.state = ''

      // this.options = []
    },
    // 搜索
    async  handleFilter () {
      // this.requestParameters.page = 1
      const { data } = await list(this.requestParameters)
      console.log(data)
      this.counts = data.counts
      this.total = data.counts
      this.dataList = data.items
      // 获取总数
      console.log(data.counts)
      this.alertText = `共 ${data.counts} 条记录`
      // this.getList()
    },
    // 删除
    removeUser (row) {
      if (this.requestParameters.page > 1 && this.dataList.length === 1) {
        this.requestParameters.page--
      }
      this.$confirm('该操作将永久删除' + ', 是否继续？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          // const res = await remove()
          await remove(row)
            .then((response) => {
              this.$message.success('删除成功')
              this.dataList.splice()

              this.getList()
            })
            .catch((response) => {
              this.$message.error('删除失败!')
            })
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    // 加载所属学科数据
    handleSubject: function () {
      this.subjectNameDate = this.dataList.subjectName
      this.formData.subjectName = this.subjectNameDate
    },
    // 创建新数据
    createData () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return false
        if (this.formData.id) {
          // 有id是编辑
          console.log(9999)
          const res = await update(this.formData)
          console.log(res)
        } else {
          // 新增功能
          let obj = this.formData
          if (this.routerId) {
            console.log(999, this.routerId)
            obj = {
              subjectID: +this.routerId,
              directoryName: this.formData.directoryName
            }
          }
          const res = await add(obj)
          console.log(res)
          this.formData = {
            ...this.formData,
            ...res.data
          }
          this.$message.success('创建新数据成功')
        }
        this.getList()

        this.closeDialog()
      })
    },
    addlist () {

    },
    updatelist () {

    }
  }
}
</script>

<style lang="scss" scoped >
  .container {
    .pagination {
      margin: 20px ;
      float: right;
    }
  }
</style>
